package com.changgou.oauth.config;

import com.changgou.oauth.util.JwtToken;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @ClassName FeignOauth2RequestInterceptor
 * @Description 获取本次的请求头信息
 * @Author 传智播客
 * @Date 12:28 2019/11/23
 * @Version 2.1
 **/
@Component
public class FeignOauth2RequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        // 获取其他的请求头信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null){
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()){
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                // 将获取到的头信息放入到feign
                template.header(headerName, headerValue);
            }
        }

        // 生成带有管理员权限的令牌 Authorization
        String token = JwtToken.adminJwt();
        System.out.println("token:" + token);
        template.header("Authorization", "bearer " + token);
    }
}
